package com.wyp168.juc;

import lombok.SneakyThrows;

/**
 * @ClassName NotifyDemo
 * @Description TODO
 * @Author wyp168
 * @Date 2022/7/8 09:28
 */
public class NotifyDemo {
    public static volatile Object resourceA = new Object();


    public static void main(String[] args) throws InterruptedException {

        Thread threadA = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                System.out.println("ThreadA try to get the resourceA lock");
                synchronized (resourceA) {
                    System.out.println("ThreadA has gotten the resourceA lock");
                    try{
                        System.out.println("ThreadA wait by resourceA");
                        resourceA.wait();
                        //ThreadA sleep 3 seconds
//                        Thread.sleep(3000);
//                        System.out.println("ThreadA release resourceA lock");
//                        resourceA.notify();
                    } catch (Exception e) {
                        throw new RuntimeException();
                    }
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("ThreadB try to get the resourceA lock");

                synchronized (resourceA) {
                    System.out.println("ThreadB has gotten the resourceA lock");
                    System.out.println("ThreadB wait by resourceA");

                    try {
                        resourceA.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("ThreadC try to get resourceA lock");
                synchronized (resourceA) {
                    System.out.println("ThreadC has gotten the resourceA lock");
                    System.out.println("ThreadC notify the thread for resourceA...");
                    resourceA.notifyAll();
                }
            }
        });

        threadA.start();
        threadB.start();

        Thread.sleep(1000);

        threadC.start();
    }
}
